<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>霓虹聊天室</title>
    <link rel="stylesheet" href="/static/css/index.css">
    <link rel="stylesheet" href="/static/js/layer/theme/default/layer.css">
    <script src="/static/js/jquery-3.7.1.min.js"></script>
    <script src="/static/js/layer/layer.js"></script>
    <script src="/static/js/axios.min.js"></script>
    <script src="/static/js/vue.global.js"></script>
<body>
    <div class="app-container">
        <!-- 好友列表侧边栏 -->
        <div class="friends-sidebar">
            <div class="sidebar-header">
                <h2 class="neon-title">好友列表</h2>
                <a style="text-decoration: none" class="logout-btn neon-btn" href="{% url 'logout' %}">
                    <i class="fa fa-sign-out"></i> 退出登录
                </a>
            </div>

            <div class="search-box">
                <input type="text" placeholder="搜索好友...">
                <i class="fa fa-search"></i>
            </div>

            <div class="friends-list">
                <h3>在线好友</h3>
                <ul>
                    <li :class="{active:index === mark}" v-for="(user,index) in userList" @click="setUser(index,user.id)">
                        <img src="/static/avater/圣洁.jpg" alt="好友头像">
                        <div class="friend-info">
                            <span class="name" v-text="user.username"></span>
                            <span class="last-msg" v-text="user.text"></span>
                        </div>
                        <span class="online-dot"></span>
                    </li>
                </ul>

                <h3>离线好友</h3>
                <ul>
                    <li>
                        <img src="/static/avater/圣洁.jpg" alt="好友头像">
                        <div class="friend-info">
                            <span class="name">赵伟</span>
                            <span class="last-msg">3小时前</span>
                        </div>
                    </li>
                    <li>
                        <img src="/static/avater/圣洁.jpg" alt="好友头像">
                        <div class="friend-info">
                            <span class="name">陈静</span>
                            <span class="last-msg">昨天</span>
                        </div>
                    </li>
                </ul>
            </div>
        </div>

        <!-- 主聊天区域 -->
        <div class="main-content">
            <!-- 移动端菜单按钮 -->
            <button class="mobile-menu-btn neon-btn">
                <i class="fa fa-bars"></i>
            </button>

            <div class="chat-container">
                <!-- 聊天室头部 -->
                <div class="chat-header">
                    <div class="current-chat-info">
                        <img src="/static/avater/圣洁.jpg" alt="当前聊天对象头像" class="small-avatar">
                        <h1 class="neon-title" v-text="user"></h1>
                    </div>
                    <div class="online-indicator">
                        <span class="dot"></span>
                        <span>在线</span>
                    </div>
                </div>

                <!-- 聊天消息区域 -->
                <div class="chat-messages">
                    <!-- 接收的消息 - 头像在左侧 -->
                    <div class="message" :class="{received:item.send_id !== selfId,sent:item.send_id === selfId}"
                         v-for="item in textList">
                        <img v-if="item.send_id !==selfId " src="/static/avater/圣洁.jpg" alt="对方头像" class="avatar">
                        <div class="message-bubble">
                            <p v-text="item.text"></p>
                            <span class="time" v-text="formatDate(item.created_time)"></span>
                        </div>
                        <img v-if="item.send_id ===selfId" src="/static/avater/地缘.jpg" alt="我的头像" class="avatar">
                    </div>
                </div>

                <!-- 消息输入区域 -->
                <div class="chat-input">
                    <input type="text" placeholder="输入消息..." v-model="text" @keydown.enter="sendMsg">
                    <button class="send-btn neon-btn" @click="sendMsg">
                        <i class="fa fa-paper-plane">发送</i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</body>
<script>
    Vue.createApp({
        data(){
            return{
                selfId:{{ request.user.pk }},
                socket:'',
                text:'',
                id:0,
                userList:[],
                mark:0,
                textList:[],
                user:[]
            }
        },
        methods:{
            socketClient(){
                this.socket = new WebSocket(`ws://192.168.11.138:8000/room/${this.id}/`)
                this.socket.onmessage = (event) => {
                    this.getMsg()
                    this.downScroll()
                }

            },
            sendMsg(){
                if(this.text === ''){
                    layer.msg('请输入消息')
                    return
                }
                axios.post("{% url 'send_msg' %}",{'text':this.text,'id':this.id},{
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).then(ret => {
                    if(ret.data.code === 200){
                        layer.msg(ret.data.msg)
                        this.socket.send(this.text)
                        this.text = ''
                        this.getMsg()
                    }else{
                        layer.msg(ret.data.msg)
                    }
                })
            },

            getUser(){
                axios.get("{% url 'get_user' %}").then(ret => {
                    if(ret.data.code === 200){
                        this.userList = ret.data.userList
                        this.id = this.userList[0].id
                    }
                })
            },
            getMsg(){
                axios.get("{% url 'get_msg' %}",{params:{'id':this.id}}).then(ret => {
                    if(ret.data.code === 200){
                        this.textList = ret.data.textList
                        this.user = ret.data.user
                        this.getLastMsg()
                        setTimeout(()=>{
                            this.downScroll()
                        },100)
                    }
                })
            },
            getLastMsg(){
                axios.get("{% url 'get_user' %}").then(ret => {
                    if(ret.data.code === 200){
                        this.userList = ret.data.userList
                    }
                })
            },
            setUser(index,id){
                this.mark = index
                this.id = id
                this.getMsg()
                this.socketClient()
            },
            downScroll(){

                // 滚动到容器底部（聊天内容区域是.msg，所以需要定位到该区域）
                const msgContainer = document.querySelector('.chat-messages');
                if (msgContainer) {
                    //msgContainer.scrollTop = msgContainer.scrollHeight;
                    msgContainer.scrollTo({
                        top: msgContainer.scrollHeight,
                        behavior: 'smooth'
                });
                }


                // 平滑滚动版本

            },
            formatDate(dateStr){
                    return dateStr.replace("T"," ").replace(/\.\d+$/,'').split(" ")[1].split(':',2).join(":")
                },
        },
        created(){
            this.getUser()
            setTimeout(()=>{
                this.getMsg()
            },100)
            setTimeout(()=>{
                this.socketClient()
            },100)
            setTimeout(()=>{
                this.downScroll()
            },100)
        }
    }).mount('.app-container')

</script>
</html>